<template>
  <div class="chartdom" ref="echartRef"></div>
</template>
<script>
import * as echarts from "echarts";
// 需要的数据格式
const obj = {
  name: "中游，零部件", // 名称
  status: 1, // 产业生命周期
  toYear: 70, // 今年
  prevYear: 100 //去年
};
const statusMenu = [
  {
    name: "引入期", value: 1, color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      {
        offset: 0,
        color: 'rgba(78, 179, 211, .2)'
      },
      {
        offset: 1,
        color: 'rgba(78, 179, 211, 0)'
      }
    ]),
    borderColor: 'rgba(78, 179, 211, 1)',
    titleBj:'#def1f7'
  },
  {
    name: "加速期", value: 2, color: "rgba(226, 246, 204, 1)", color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      {
        offset: 0,
        color: 'rgba(88, 144, 229, .2)'
      },
      {
        offset: 1,
        color: 'rgba(78, 179, 211, 0)'
      }
    ]),
    borderColor: 'rgba(88, 144, 229, 1)',
    titleBj:'#dbe4f3'
  },
  {
    name: "洗牌期", value: 3, color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      {
        offset: 0,
        color: 'rgba(82, 80, 213, .2)'
      },
      {
        offset: 1,
        color: 'rgba(78, 179, 211, 0)'
      }
    ]),
    borderColor: 'rgba(82, 80, 213, 1)'
  },
  {
    name: "出清期", value: 4, color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      {
        offset: 0,
        color: "rgba(247, 145, 122, .2)"
      },
      {
        offset: 1,
        color: 'rgba(78, 179, 211, 0)'
      }
    ]),
    borderColor: "rgba(247, 145, 122, 1)"
  },
  {
    name: "稳态期", value: 5, color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      {
        offset: 0,
        color: 'rgba(103, 194, 58, 0.2)'
      },
      {
        offset: 1,
        color: 'rgba(78, 179, 211, 0)'
      }
    ]),
    borderColor: "rgba(247, 145, 122, 1)"
  },
  {
    name: "成熟后期", value: 6, color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      {
        offset: 0,
        color: "rgba(127, 116, 211, .2)"
      },
      {
        offset: 1,
        color: 'rgba(78, 179, 211, 0)'
      }
    ]),
    borderColor: "rgba(127, 116, 211, 1)"
  },
  {
    name: "衰退期", value: 7, color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      {
        offset: 0,
        color: "rgba(219, 221, 221, .2)"
      },
      {
        offset: 1,
        color: 'rgba(78, 179, 211, 0)'
      }
    ]),
    borderColor: "rgba(219, 221, 221, 1)"
  }
];

export default {
  name: "",
  props: {
    // 今年数据
    data: {
      type: Array,
      default: () => []
    },
    // 柱子宽度
    barWidth: {
      type: Number,
      default: 15
    },
    // 曲线样式
    smooth: {
      type: Boolean,
      default: false
    },
    symbolSize: {
      type: Number,
      default: 5
    }
  },
  data() {
    return {
      myChart: null,
      activeYear: [],
      prevYear: [],
      xData: [],
      markArea: [],
      fontSize:14
    };
  },
  watch: {
    data(newVal) {
      this.init();
    }
  },
  computed: {},
  mounted() {
    this.init();
  },
  unmounted() {
    window.removeEventListener("resize", this.getResize);
  },
  methods: {
    // 初始化，数据变动皆调用
    init() {
      this.initData();
      if (!this.myChart) {
        this.initChat();
      }
      this.initOption();
    },
    initChat() {
      this.myChart = echarts.init(this.$refs.echartRef);
      window.addEventListener("resize", this.getResize);
    },
    // 根据传入的数据格式，修改组件需要的格式
    initData() {
      const obj = {
        name: "中游，零部件", // 名称
        status: 1, // 产业生命周期
        toYear: 70, // 今年
        prevYear: 100 //去年
      };
      console.log(this.data);
      this.activeYear = [];
      this.prevYear = [];
      this.markArea = [];
      this.xData = [];
      const sortData = this.data; //.sort((a, b) => a.status - b.status);
      console.log(this.data);
      let preData
      // 循环加入数组， 并且生成 mark的值（背景位置）
      this.markArea = sortData.reduce((result, item, index) => {
        const toYear = item.toYear ? Math.floor(item.toYear * 100) / 100 : 0;
        const prevYear = item.prevYear
          ? Math.floor(item.prevYear * 100) / 100
          : 0;
        this.activeYear.push(toYear);
        this.prevYear.push(prevYear);
        this.xData.push(item.title);

        if (!result[item.status]) {
          result[item.status] = [item.title];
        } else {
          console.log(result[item.status]);
          console.log(item.status);
          result[item.status][1] = item.title;
        }
        return result;
      }, {});

      console.log(this.markArea);
    },
    getResize() {
      this.myChart.resize();
      console.log("屏幕宽度变化");
    },
    // 根据最大最小值，获取适合摆放文字的位置
    getMaxMinName(num1, num2) {
      const maxSize = Math.max(num1, num2);
      const minSize = Math.min(num1, num2);
      const gap = maxSize % 100;
      const tops = [maxSize, "-"];
      const bottoms = ["-", minSize];
      // 如果下面很宽敞，则放置在下面
      if (minSize > 50) {
        return bottoms;
      } else if (maxSize < 50) {
        return tops;
      } else if (gap > minSize) {
        // 如果上面空隙大于下面空隙，则放置在上面
        return tops;
      } else {
        return bottoms;
      }
    },
    // 根据数据生成柱子
    getBarData(active, prev) {
      const length = Math.max(active.length, prev.length);
      const redSize = []; // 红色柱子
      const blueBar = []; // 蓝色柱子
      let minBar = []; // 透明柱子
      const maxName = [];
      const minName = [];

      Array(length)
        .fill(0)
        .forEach((_, index) => {
          const start = active[index];
          const end = prev[index];
          const differ = start - end;

          minBar.push(Math.min(start, end));
          // - 用于 hover的时候隐藏对于的值
          redSize.push(differ < 0 ? Math.abs(differ).toFixed(2) : "-");
          blueBar.push(differ >= 0 ? Math.abs(differ).toFixed(2) : "-");
          const [max, min] = this.getMaxMinName(start, end);
          maxName.push(max);
          minName.push(min);
        });




      return [minBar, redSize, blueBar, maxName, minName];
    },
    // 获取echarts 数据并且写入
    initOption() {
      this.myChart.clear();
      // 图表配置项
      const option = this.getOption();
      // 渲染配置
      this.myChart.setOption(option);
      const zoomSize = 2;

      this.myChart.on("click", params => {
        const start = this.activeYear[
          Math.max(params.dataIndex - zoomSize / 2, 0)
        ];
        console.log(start);
        this.myChart.dispatchAction({
          type: "dataZoom",
          startValue: start,
          endValue: this.activeYear[
            Math.min(
              params.dataIndex + zoomSize / 2,
              this.activeYear.length - 1
            )
          ]
        });
      });
    },
    /**
     * 获取今年的数据
     * 较为特殊是需要把背景 加速期、出清期等展示出来
     */
    getMarkArea() {
      let prevKey = null; // 解决1-2 3-4   2-3中间存在大片间隙问题
      const length = Object.keys(this.markArea).length - 1;
      const arr = Object.keys(this.markArea).map((key, index) => {
        const item = this.markArea[key];
        const aData = statusMenu.find(v => v.value == key);
        const obj = [
          {
            name: aData && aData.name,
            xAxis: index == 0 ? 'min' : item[0],
            emphasis: {
              disabled: true
            },
            label: {
              show: true,
              color: "#000000",
              // position: 'inside',
              backgroundColor: aData.color, // 放大后文字叠加，添加背景遮挡
              borderColor: "transparent",
              padding: [15, 5],
              height: '100%',
              offset: [20, 20],
              position: "insideTopLeft",
              fontSize: 18,
              // rotate:90,
              formatter: function (value) {
                return value.name
                  .slice(0, 10)
                  .split("")
                  .join("\n"); //垂直显示
              }
            },
            itemStyle: {
              color: aData.color,

              borderWidth: 10,
              borderColor: '#fff',  // 设置边框颜色
            },
            z:index
          },
          {
            xAxis: index == length ? 'max' : item[1]
          },

        ];
        prevKey = item[1];
        return obj;
      });
      console.log("area数据");
      console.log(arr);
      console.log(this.activeYear);
      return {
        itemStyle: {
          color: "rgba(255, 173, 177, 0.4)",
          fontSize: 24,
          rotation: -40,
          offset: [10, 50]
        },
        data: arr
      };
    },
    getMarkArea1() {
      let prevKey = null; // 解决1-2 3-4   2-3中间存在大片间隙问题
      const length = Object.keys(this.markArea).length - 1;
      const arr = Object.keys(this.markArea).map((key, index) => {
        const item = this.markArea[key];
        const aData = statusMenu.find(v => v.value == key);
        const obj = [
          {
            name: aData && aData.name,
            xAxis: index == 0 ? 'min' : item[0],
            emphasis: {
              disabled: true
            },
            label: {
              show: false,
            },
            itemStyle: {
              color: aData.borderColor,
              borderWidth: 0,
              borderColor: '#fff',  // 设置边框颜色
              offset: [10, 10],
            },
            yAxis: 100,
          },
          {
            xAxis: index == length ? 'max' : item[1],
            yAxis: 98.5,
          },

        ];
        prevKey = item[1];
        return obj;
      });
      console.log("area数据");
      console.log(arr);
      console.log(this.activeYear);
      return {
        itemStyle: {
          color: "rgba(255, 173, 177, 0.4)",
          fontSize: 24,
          rotation: -40,
          offset: [10, 50]
        },
        data: arr
      };
    },
    // 由于中文会乱位置，故需要改成数字，然后再提取中文显示
    getTitle(name) {
      const data = this.data.find(v => v.title == name)
      console.log(data);
      return data ? data.name : name
    },

    getData() {
      let arrData = [];
      const that = this
      // 只有两年才存在，才需要柱状图
      if (
        this.prevYear &&
        this.prevYear.length > 0 &&
        this.activeYear &&
        this.activeYear.length > 0
      ) {
        const [minBar, redSize, blueBar, maxName, minName] = this.getBarData(
          this.activeYear,
          this.prevYear
        );

        console.log(this.getMarkArea());
        const barArr = [

          {
            name: "差值",
            type: "bar",
            data: minBar,
            markArea: this.getMarkArea1(),
            barWidth: this.barWidth,
            stack: "Total",
            silent: true,
            tooltip: {
              show: false
            },
            itemStyle: {
              borderColor: "transparent",
              color: "transparent",
              zIndex: 10
            },
            emphasis: {
              itemStyle: {
                borderColor: "transparent",
                color: "transparent",
                zIndex: 10
              }
            },
            z:10
          },
          {
            name: "较去年下降",
            type: "bar",
            stack: "Total",
            data: redSize,
            barWidth: this.barWidth,
            markArea: this.getMarkArea(),
            itemStyle: {
              borderColor: "transparent",
              color: "rgba(255, 93, 89, 1)",
              zIndex: 10
            },
            z: 100
          },
          {
            name: "较去年上升",
            type: "bar",
            stack: "Total",
            data: blueBar,
            barWidth: this.barWidth,
            itemStyle: {
              borderColor: "transparent",
              color: "rgba(0, 191, 151, 1)",
              zIndex: 10
            },
            z: 100
          },
          {
            name: "显示在上面区域",
            type: "line",
            tooltip: {
              show: false
            },
            label: {
              show: true,
              position: "top",
              offset: [0, -20],
              color: "#333",
              fontSize:this.fontSize,
              formatter: function (params) {
                const title = that.getTitle(params.name)

                console.log(title);
                return String(title).slice(0, 10).split("").join("\n"); //垂直显示
              }
            },
            silent: true,
            itemStyle: {
              borderColor: "transparent",
              color: "transparent"
            },

            emphasis: {
              itemStyle: {
                borderColor: "transparent",
                color: "transparent"
              }
            },
            data: maxName
          },
          {
            name: "显示在下面区域",
            type: "line",
            tooltip: {
              show: false
            },
            label: {
              show: true,
              position: "bottom",
              offset: [0, 10],
              color: "#333",
              fontSize:this.fontSize,
              formatter: function (params) {
                const title = that.getTitle(params.name)


                return String(title).slice(0, 10).split("").join("\n"); //垂直显示
              }
            },
            silent: true,
            itemStyle: {
              borderColor: "transparent",
              color: "transparent"
            },

            emphasis: {
              itemStyle: {
                borderColor: "transparent",
                color: "transparent"
              }
            },
            data: minName
          }
        ];
        arrData.push(...barArr);
      }
      if (this.activeYear && this.activeYear.length > 0) {
        arrData.push({
          name: "本年",
          type: "line",
          symbolSize: this.symbolSize,
          symbol: "circle",
          data: this.activeYear,

          smooth: this.smooth,
          lineStyle: {
            lineOffset: 100, // 设置线条向右偏移10个像素
          },
          itemStyle: {
            width: 10,
            shadowColor: "rgba(0, 0, 0, 0.2)",

            shadowBlur: 10,
            shadowOffsetX: 20,
            shadowOffsetY: 10,
            color: "rgba(0, 78, 162, 1)",

          },
          label: {
            show: false,
            precision: 1,
            position: "bottom",
            fontSize: 12,
            color: "#000",
            valueAnimation: true,
            formatter: function (params) {
              console.log(params);
              const length = params.name.toString().length;
              const name =
                length > 10 ? params.name.slice(0, 10) + "." : params.name;
              return name.split("").join("\n"); //垂直显示
            }
          }
        });
        // const arr1 = Array(this.activeYear.length).fill(1);
        // const newObj = {
        //   name: "",
        //   data: this.activeYear,
        //   type: "bar",
        //   barWidth: 10,
        //   tooltip: {
        //     show: false
        //   },
        //   markArea: this.getMarkArea(),
        //   itemStyle: {
        //     borderColor: "transparent",
        //     color: "transparent"
        //   }
        // };
        // arrData.push(newObj);
      }
      // 去年的线
      if (this.prevYear && this.prevYear.length > 0) {
        arrData.push({
          name: "上年",
          type: "line",
          smooth: this.smooth,
          symbolSize: this.symbolSize,
          symbol: "circle",
          data: this.prevYear,
          itemStyle: {
            color: "rgba(141, 214, 207, 1)"
          }
        });
      }
      return arrData;
    },
    getOption() {
      const that = this
      return {
        dataZoom: [
          {
            type: "inside", // "slider",
            xAxisIndex: 0
          }
        ],
        title: {
          text: "产业生命周期",
          show: true,
          left: 30,
          top: 20,
          textStyle: {
            color: '#000',
            fontSize:16,
          }
        },
        tooltip: {
          trigger: "axis",
          formatter: function (params) {
            console.log('hahahah');
            console.log(params);
            const title = that.getTitle(params[0].name)
            return title
          }
        },
        legend: {
          top: "30",
          right: "200",
          textStyle: {
            fontSize: 14
          },
          itemHeight: 12,
          data: ["本年", "上年", "较去年上升", "较去年下降"],

        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          top: 86,
          containLabel: true
        },
        toolbox: {
          show: true
        },
        xAxis: {
          type: "category",
          boundaryGap: true,
          // prettier-ignore
          data: this.xData,
          splitLine: {
            show: false, // 隐藏x轴的分隔线
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: false // 隐藏轴线
          },
          axisLabel: {
            show: false // 隐藏轴标签
          }
        },
        yAxis: {
          type: "value",
          max: 100,
          axisLabel: {
            formatter: "{value}.00",
            show: true, // 隐藏轴标签
            fontSize:this.fontSize,
            margin:20, // 控制轴标签距离轴线的距离
      
          },
          splitNumber: 10,
          axisTick: {
            show: false
          },

          splitLine: {
            show: false
          },
          axisLine: {
            show: false // 隐藏轴线
          },
          axisPointer: {
            snap: true
          }
        },

        series: this.getData()
      };
    }
  }
};
</script>
<style lang="scss" scoped>
.chartdom {
  width: 100%;
  height: 100%;
}
</style>
